﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.International.Converters.PinYinConverter;
using System.Security.Cryptography;

namespace ZhCun.Framework.Common.Helpers
{
    public class StringHelper
    {
        /// <summary>
        /// 获取汉子的拼音
        /// </summary>
        /// <param name="hz">汉字</param>
        /// <param name="isSimple">是否是简拼  true: 为简拼,false为全拼</param>        
        public static string GetPinYin(string hz, bool isSimple)
        {
            if (hz == null) return string.Empty;
            //引用  Microsoft.International.Converters.PinYinConverter 命名空间
            //文件: ChnCharInfo.dll
            StringBuilder sb = new StringBuilder();
            foreach (char hzch in hz)
            {
                if (ChineseChar.IsValidChar(hzch)) //判断是否是中文
                {
                    ChineseChar ch = new ChineseChar(hzch);

                    //s = ch.Pinyins[0].ToString();  //下标用来判断多音字
                    //s += s.Substring(0, s.Length - 1);  //最后一位是声调,去掉
                    if (isSimple) //如果是简拼
                    {
                        sb.Append(ch.Pinyins[0].Substring(0, 1).ToUpper());
                    }
                    else
                    {
                        //去掉音调后的拼音
                        sb.Append(ch.Pinyins[0].Remove(ch.Pinyins[0].Length - 1));
                    }
                }
                else
                {
                    sb.Append(hzch.ToString());
                }
            }
            return sb.ToString();
        }
        /// <summary>
        /// 获取汉子的简拼
        /// </summary>
        public static string GetPinYin(string hz)
        {
            return GetPinYin(hz, true);
        }
        /// <summary>
        /// 获得MD5加密字符串
        /// </summary>
        public static string MD5EnString(string str)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(System.Text.Encoding.GetEncoding(Constants.MD5EncodingText).GetBytes(str));
            return System.Text.Encoding.GetEncoding(Constants.MD5EncodingText).GetString(result);
        }
        /// <summary>
        /// 使用Base64编码字符
        /// </summary>
        public static string Base64EnString(string str)
        {
            byte[] bytes = Encoding.GetEncoding(Constants.Base64EncodingText).GetBytes(str);
            return Convert.ToBase64String(bytes);
        }
        /// <summary>
        /// 使用Base64解码
        /// </summary>
        public static string Base64DeString(string str)
        {
            byte[] outputb = Convert.FromBase64String(str);
            string orgStr = Encoding.GetEncoding(Constants.Base64EncodingText).GetString(outputb);
            return orgStr;
        }
    }
}
